<?php

session_start();

	if(!isset($_SESSION['logged']) && !isset($_POST['estadoLogin'])){
		include_once 'include/tags.php';
		include_once 'vista/login.html.php';			
	}
	else{ //No tenemos sesion pero venimos del formulario login.html.php
		include_once '../bbdd/bbdd.php';
		include_once '../include/config.php';
		include_once '../include/tags.php';
		
		$db = new bbdd($db_host, $db_user_admin, $db_pass_admin, $db_name);
		
		$db->creaConexion();
		$db->seleccionaBD();
		
		$username = $_POST['username'];
		$password = $_POST['password'];
		
		$query = "SELECT username, adminpriv, id, enable FROM users where username = '".$username."' and password = '".$password."';";
		
		$result = $db->ejecutaConsulta($query);
		if(!$result){
			$smg = "ERROR : FALLO EN EL SERVIDOR<BR>";
			include_once '../index.php';
		}else{
			$i = 0;
			while ($valor = $db->recuperaValoresConsulta($result)){
				$usernameDB = $valor['username'];  
				$havePriv = $valor['adminpriv'];
				$idUser = $valor['id'];
				$enable = $valor['enable'];
				$i++;
			}
			$db->libera($result);
			
			if(strlen($usernameDB)!=0 && strcmp($enable, "Y")==0){ //Existe un usuario con ese username y password y no esta deshabilitado
				session_start();
				if(strcmp($havePriv,"Y")==0){
					//tipo de usuario admin
					$_SESSION['logged']="YES";
					$_SESSION['username']= $usernameDB;
					$_SESSION['permisos']="1";
					$_SESSION['idUser']= $idUser;
					include_once 'home.php';
				}
				if(strcmp($havePriv,"N")==0){
					//tipo de usuario comun
					$_SESSION['logged']="YES";
					$_SESSION['username']= $usernameDB;
					$_SESSION['permisos']="0";
					$_SESSION['idUser']= $idUser;
					include_once 'home.php';
				}
			}else{
				include_once '../include/tags.php';
				if (strcmp($enable, "N")==0){
					$msg = "<br>ERROR : Tu cuenta ha sido deshabilitada<BR>";
				}else{
					$msg = "<br>ERROR : Los datos introducidos son incorrectos<BR>";	
				}
				
				include_once '../vista/login.html.php';
			}
		}
		$db->cierraConexion();
	}
?>
